// 圣经问答游戏 - 分享功能

class ShareSystem {
    constructor() {
        this.shareModal = null;
        this.shareCard = null;
        this.initializeShareModal();
    }

    // 初始化分享弹窗
    initializeShareModal() {
        this.shareModal = document.getElementById('shareModal');
        this.shareCard = document.getElementById('shareCard');
        
        // 绑定关闭事件
        const closeBtn = this.shareModal?.querySelector('.close');
        if (closeBtn) {
            closeBtn.onclick = () => this.hideShareModal();
        }
        
        // 点击背景关闭
        if (this.shareModal) {
            this.shareModal.onclick = (e) => {
                if (e.target === this.shareModal) {
                    this.hideShareModal();
                }
            };
        }
        
        // 绑定分享按钮事件
        const copyBtn = document.getElementById('copyShareText');
        const downloadBtn = document.getElementById('downloadShareImage');
        
        if (copyBtn) copyBtn.onclick = () => this.copyShareText();
        if (downloadBtn) downloadBtn.onclick = () => this.downloadShareImage();
    }

    // 显示分享弹窗
    showShareModal(gameStats) {
        if (!this.shareModal) return;
        
        // 回填难度
        if (gameStats && !gameStats.difficulty && window.scoringSystem?.difficulty) {
            gameStats.difficulty = window.scoringSystem.difficulty;
        }
        
        // 更新分享卡片内容
        this.updateShareCard(gameStats);
        
        // 显示弹窗
        this.shareModal.classList.add('show');
        
        // 播放音效
        if (window.quizGame) {
            quizGame.playSound('click');
        }
    }

    // 隐藏分享弹窗
    hideShareModal() {
        if (this.shareModal) {
            this.shareModal.classList.remove('show');
        }
    }

    // 更新分享卡片内容
    updateShareCard(gameStats) {
        const sharePreview = document.getElementById('sharePreview');
        if (!sharePreview) {
            console.error('❌ 找不到分享预览元素');
            return;
        }
        
        // 回填难度
        if (gameStats && !gameStats.difficulty && window.scoringSystem?.difficulty) {
            gameStats.difficulty = window.scoringSystem.difficulty;
        }
        
        // 获取难度名称（覆盖两套命名）
        const difficultyNames = {
            explorer: '探索者',
            adventurer: '冒险家',
            hero: '英雄',
            legend: '传奇',
            beginner: '入门级',
            intermediate: '进阶级',
            expert: '专家级'
        };
        
        const difficulty = difficultyNames[gameStats.difficulty] || (gameStats.difficulty ?? '未知');
        
        // 获取等级信息
        const grade = window.scoringSystem ? 
            window.scoringSystem.getScoreGrade(gameStats.finalScore) : 
            { grade: 'C', title: '继续努力' };
        
        // 生成分享卡片HTML
        sharePreview.innerHTML = `
            <div class="share-card">
                <div class="share-header">
                    <h3>🌈 主日学圣经问答</h3>
                    <div class="share-badge">${grade.grade}</div>
                </div>
                <div class="share-content">
                    <div class="share-stat">
                        <span class="stat-icon">🎯</span>
                        <span class="stat-label">得分</span>
                        <span class="stat-value">${gameStats.finalScore}</span>
                    </div>
                    <div class="share-stat">
                        <span class="stat-icon">📚</span>
                        <span class="stat-label">难度</span>
                        <span class="stat-value">${difficulty}</span>
                    </div>
                    <div class="share-stat">
                        <span class="stat-icon">✅</span>
                        <span class="stat-label">正确率</span>
                        <span class="stat-value">${gameStats.accuracy}%</span>
                    </div>
                    <div class="share-stat">
                        <span class="stat-icon">🔥</span>
                        <span class="stat-label">最高连击</span>
                        <span class="stat-value">${gameStats.maxStreak}</span>
                    </div>
                </div>
                <div class="share-footer">
                    <p class="share-title">${grade.title}</p>
                    <p class="share-message">一起来挑战圣经知识吧！</p>
                </div>
            </div>
        `;
        
        console.log('✅ 分享卡片已生成');
    }

    // 生成分享文本
    generateShareText(gameStats) {
        // 回填难度
        if (gameStats && !gameStats.difficulty && window.scoringSystem?.difficulty) {
            gameStats.difficulty = window.scoringSystem.difficulty;
        }
        const difficultyNames = {
            explorer: '探索者',
            adventurer: '冒险家', 
            hero: '英雄',
            legend: '传奇',
            beginner: '入门级',
            intermediate: '进阶级',
            expert: '专家级'
        };
        
        const difficulty = difficultyNames[gameStats.difficulty] || (gameStats.difficulty ?? '未知');
        const grade = scoringSystem.getScoreGrade(gameStats.finalScore);
        
        const shareTexts = [
            `🎯 我在圣经问答游戏中获得了 ${gameStats.finalScore} 分！
📚 难度：${difficulty}
✅ 正确率：${gameStats.accuracy}%
🔥 最高连击：${gameStats.maxStreak} 题
🏆 等级：${grade.grade} ${grade.title}
一起来挑战吧！`,
            
            `📖 圣经问答挑战完成！
🎯 ${difficulty}难度 - ${gameStats.finalScore}分
📊 正确率 ${gameStats.accuracy}% | 连击 ${gameStats.maxStreak}题
⏱️ 用时 ${gameStats.timeTaken}秒
你能超过我吗？`,
            
            `🌟 刚完成了圣经问答游戏！
🏅 获得 ${grade.title} 等级
📈 得分：${gameStats.finalScore}
🎯 准确率：${gameStats.accuracy}%
快来测试你的圣经知识吧！`
        ];
        
        return shareTexts[Math.floor(Math.random() * shareTexts.length)];
    }

    // 复制分享文本
    async copyShareText() {
        try {
            const gameStats = scoringSystem.getGameStats();
            const shareText = this.generateShareText(gameStats);
            
            if (navigator.clipboard && window.isSecureContext) {
                // 使用现代 Clipboard API
                await navigator.clipboard.writeText(shareText);
            } else {
                // 降级方案
                this.fallbackCopyText(shareText);
            }
            
            this.showCopySuccess();
        } catch (error) {
            console.error('复制失败:', error);
            this.showCopyError();
        }
    }

    // 降级复制方案
    fallbackCopyText(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
            document.execCommand('copy');
            textArea.remove();
        } catch (error) {
            textArea.remove();
            throw error;
        }
    }

    // 显示复制成功提示
    showCopySuccess() {
        this.showToast('✅ 分享文本已复制到剪贴板！', 'success');
    }

    // 显示复制失败提示
    showCopyError() {
        this.showToast('❌ 复制失败，请手动复制分享内容', 'error');
    }

    // 下载分享图片
    async downloadShareImage() {
        try {
            const canvas = await this.generateShareImage();
            this.downloadCanvas(canvas, 'bible-quiz-result.png');
            this.showToast('✅ 分享图片已下载！', 'success');
        } catch (error) {
            console.error('生成分享图片失败:', error);
            this.showToast('❌ 生成图片失败，请稍后重试', 'error');
        }
    }

    // 生成分享图片
    async generateShareImage() {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // 设置画布尺寸
        canvas.width = 600;
        canvas.height = 800;
        
        // 获取游戏数据
        const gameStats = scoringSystem.getGameStats();
        const grade = scoringSystem.getScoreGrade(gameStats.finalScore);
        
        // 绘制背景渐变
        const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
        gradient.addColorStop(0, '#2c5aa0');
        gradient.addColorStop(1, '#d4af37');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 绘制半透明覆盖层
        ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 设置文字样式
        ctx.textAlign = 'center';
        ctx.fillStyle = 'white';
        
        // 标题
        ctx.font = 'bold 48px "Noto Sans SC", sans-serif';
        ctx.fillText('圣经问答游戏', canvas.width / 2, 100);
        
        // 分数
        ctx.font = 'bold 72px "Noto Sans SC", sans-serif';
        ctx.fillText(gameStats.finalScore, canvas.width / 2, 220);
        ctx.font = '24px "Noto Sans SC", sans-serif';
        ctx.fillText('最终得分', canvas.width / 2, 250);
        
        // 等级徽章
        ctx.font = 'bold 36px "Noto Sans SC", sans-serif';
        ctx.fillStyle = grade.color;
        ctx.fillRect(canvas.width / 2 - 100, 280, 200, 60);
        ctx.fillStyle = 'white';
        ctx.fillText(`${grade.grade} ${grade.title}`, canvas.width / 2, 320);
        
        // 统计信息
        ctx.fillStyle = 'white';
        ctx.font = '28px "Noto Sans SC", sans-serif';
        
        const difficultyNames = {
            beginner: '入门级',
            intermediate: '进阶级',
            expert: '专家级',
            explorer: '探索者',
            adventurer: '冒险家',
            hero: '英雄',
            legend: '传奇'
        };
        // 回填难度
        if (!gameStats.difficulty && window.scoringSystem?.difficulty) {
            gameStats.difficulty = window.scoringSystem.difficulty;
        }
        
        const stats = [
            `难度：${difficultyNames[gameStats.difficulty] || gameStats.difficulty || '未知'}`,
            `正确率：${gameStats.accuracy}%`,
            `最高连击：${gameStats.maxStreak} 题`,
            `用时：${gameStats.timeTaken} 秒`
        ];
        
        stats.forEach((stat, index) => {
            ctx.fillText(stat, canvas.width / 2, 400 + index * 50);
        });
        
        // 底部文字
        ctx.font = '24px "Noto Sans SC", sans-serif';
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.fillText('一起来挑战吧！', canvas.width / 2, 650);
        
        // 日期
        ctx.font = '18px "Noto Sans SC", sans-serif';
        ctx.fillText(new Date().toLocaleDateString('zh-CN'), canvas.width / 2, 720);
        
        return canvas;
    }

    // 下载画布为图片
    downloadCanvas(canvas, filename) {
        const link = document.createElement('a');
        link.download = filename;
        link.href = canvas.toDataURL('image/png');
        link.click();
    }

    // 显示提示消息
    showToast(message, type = 'info') {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        
        // 样式
        Object.assign(toast.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '12px 24px',
            borderRadius: '8px',
            color: 'white',
            fontSize: '16px',
            fontWeight: '500',
            zIndex: '10000',
            opacity: '0',
            transform: 'translateY(-20px)',
            transition: 'all 0.3s ease',
            maxWidth: '300px',
            wordWrap: 'break-word'
        });
        
        // 根据类型设置背景色
        const colors = {
            success: '#27ae60',
            error: '#e74c3c',
            info: '#3498db',
            warning: '#f39c12'
        };
        toast.style.backgroundColor = colors[type] || colors.info;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 显示动画
        setTimeout(() => {
            toast.style.opacity = '1';
            toast.style.transform = 'translateY(0)';
        }, 100);
        
        // 自动移除
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-20px)';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }

    // 分享到微信（生成二维码）
    shareToWeChat(gameStats) {
        const shareText = this.generateShareText(gameStats);
        const encodedText = encodeURIComponent(shareText);
        
        // 这里可以集成微信分享SDK或生成二维码
        // 由于是静态页面，我们提供复制链接的方式
        this.showToast('请复制分享文本到微信', 'info');
        this.copyShareText();
    }

    // 分享到微博
    shareToWeibo(gameStats) {
        const shareText = this.generateShareText(gameStats);
        const url = encodeURIComponent(window.location.href);
        const weiboUrl = `https://service.weibo.com/share/share.php?url=${url}&title=${encodeURIComponent(shareText)}`;
        
        window.open(weiboUrl, '_blank', 'width=600,height=400');
    }

    // 分享到QQ空间
    shareToQzone(gameStats) {
        const shareText = this.generateShareText(gameStats);
        const url = encodeURIComponent(window.location.href);
        const qzoneUrl = `https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${url}&title=${encodeURIComponent(shareText)}`;
        
        window.open(qzoneUrl, '_blank', 'width=600,height=400');
    }

    // 生成成就分享内容
    generateAchievementShareText(achievement) {
        const shareTexts = [
            `🎉 我在圣经问答游戏中解锁了新成就！
🏆 ${achievement.icon} ${achievement.name}
📝 ${achievement.description}
快来挑战吧！`,
            
            `✨ 成就达成！
🎯 ${achievement.name} ${achievement.icon}
💡 ${achievement.description}
你也来试试吧！`,
            
            `🌟 新徽章获得！
🏅 ${achievement.icon} ${achievement.name}
一起来测试圣经知识吧！`
        ];
        
        return shareTexts[Math.floor(Math.random() * shareTexts.length)];
    }

    // 分享成就
    shareAchievement(achievement) {
        const shareText = this.generateAchievementShareText(achievement);
        
        if (navigator.share) {
            // 使用原生分享API（移动设备）
            navigator.share({
                title: '圣经问答游戏 - 新成就',
                text: shareText,
                url: window.location.href
            }).catch(console.error);
        } else {
            // 复制到剪贴板
            this.fallbackCopyText(shareText);
            this.showToast('✅ 成就分享内容已复制！', 'success');
        }
    }

    // 检查分享支持
    isNativeShareSupported() {
        return 'share' in navigator;
    }

    // 获取分享统计
    getShareStats() {
        // 这里可以添加分享统计逻辑
        // 比如记录分享次数、分享渠道等
        return {
            totalShares: 0,
            platforms: {
                copy: 0,
                weibo: 0,
                qzone: 0,
                wechat: 0
            }
        };
    }
}

// 创建全局分享系统实例
window.shareSystem = new ShareSystem();